from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework import permissions
from logs.models import *
# Create your views here.
import time
import datetime
import os
import uuid
from threading import Thread

from logs.utils import get_cell_data, get_group_data

class DataUpload(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    def post(self, request, *args, **kwargs):
        file = request.FILES.get('file', None)
        if file is not None:
            save_path = os.path.join('temp',  str(time.time()))
            if not os.path.exists('temp'):
                os.makedirs('temp')
            with open(save_path,'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            tid = str(uuid.uuid4())
            task = Tasks()
            task.task = tid
            task.state = 1
            task.msg = 'Waiting'
            task.start = datetime.datetime.now()
            task.save()
            th = Thread(target=self.process_file, args=(save_path, task))
            # self.process_file(file)
            th.start()
            return JsonResponse({'message':'ok', 'task': task.task})
        return JsonResponse({'message': 'no files'})
    def delete(self, request, *args, **kwargs):
        Logs.objects.all().delete()
        return JsonResponse({'message': 'ok'})
        
    def process_file(self, save_path, task):
        # print(fin.name)
        task.msg = 'Start process'
        task.state = 2
        task.save()
        
        try:
            with open(save_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                header = lines[0]
                header = header.strip().split(',')
                name_map = {
                    'cell':-1, 'temp':-1, 'v':-1, 'i':-1, 'soh':-1, 'energy':-1, 't':-1
                }
                for i, h in enumerate(header):
                    name_map[h] = i
                
                if name_map['cell'] == -1:
                    return JsonResponse({
                        'code': 1,
                        'message': 'Do not found Cell'
                    })

                for line in lines[1:]:
                    seq = line.strip().split(',')
                    cell = Cell.objects.get_or_create({'name': seq[name_map['cell']]}, name=seq[name_map['cell']])[0]
                    cell.save()
                    log = Logs()
                    log.cell = cell
                    log.temp = float(seq[name_map['temp']])
                    log.v = float(seq[name_map['v']])
                    log.energy = float(seq[name_map['energy']])
                    log.soh = float(seq[name_map['soh']])
                    log.i = float(seq[name_map['i']])
                    if name_map['t'] == -1:
                        log.t = datetime.datetime.now()
                    else:
                        log.t = datetime.datetime.fromisoformat(seq[name_map['t']])
                    log.save()
        except Exception as e:
            task.state = -2
            task.msg = 'Error when saving: ' + str(e)[:100]
            task.end = datetime.datetime.now()
            print(e)
            task.save()
            
        try:
            os.remove(save_path)
        except:
            pass
        if task.state > 0:
            task.state = 0
            task.msg = 'Finish!'
            task.end = datetime.datetime.now()
            task.save()

class ZXJCDataGet(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        if request.GET.get('cell', None) is None:
            return JsonResponse({
                    'code': 0,
                    'data': []
                })
        else:
            try:
                # cell = Cell.objects.get(name = request.GET.get('cell'))
                # logs = Logs.objects.filter(cell = cell).order_by('t')
                cell = int(request.GET.get('cell')) - 1
                data = get_cell_data(cell)
                return JsonResponse({
                    'code': 0,
                    'data': data
                })
            except Exception as e:
                return JsonResponse({
                    'message': str(e),
                    'code': 1,
                })
        # try:
        #     res = {
        #         'code': 0,
        #         'data':[]
        #     }
        #     if logs.count() == 0:
        #         return JsonResponse(res)
            
        #     res['data'] = [ l.to_json(include_t = True) for l in logs.iterator() ]
        #     return JsonResponse(res)
            
        # except Exception as e:
        #     return JsonResponse({
        #         'message': str(e),
        #         'code': 1,
        #     })



class DCCDataGet(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        if request.GET.get('group', None) is None:
            return JsonResponse({
                    'code': 0,
                    'data': []
                })
        else:
            try:
                # cell = Cell.objects.get(name = request.GET.get('cell'))
                # logs = Logs.objects.filter(cell = cell).order_by('t')
                group = int(request.GET.get('group')) -1
                data = get_group_data(group)
                return JsonResponse({
                    'code': 0,
                    'data': data
                })
            except Exception as e:
                return JsonResponse({
                    'message': str(e),
                    'code': 1,
                })

class TaskGet(APIView):

    permission_classes = (permissions.IsAuthenticated,)

    def get(self, requst, *args, **kwargs):
        try:
            # print(requst.GET)
            task = Tasks.objects.get(task=requst.GET.get('tid'))
            return JsonResponse({
            'task': {
                    'state': task.state,
                    'tid': task.task,
                    'msg': task.msg,
                    'start': task.start,
                    'duration': task.duration,
                },
            'code': 0
            })
        except:
            return JsonResponse({'message': 'Not Found', 'code': 1})